package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.mapper.SpecMapper;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.pojo.SpecGroup;
import com.leyou.item.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecService {


    @Autowired
    private SpecMapper specMapper;

    @Autowired
    private SpecParamMapper specParamMapper;

    /**
     * 根据分类的id，查询对应的规格参数组信息
     * @param cid
     * @return
     */
    public List<SpecGroupDTO> queryGroupByCategory(Long cid) {

        SpecGroup record = new SpecGroup();
        record.setCid(cid);

        List<SpecGroup> specGroupList = this.specMapper.select(record);

        if (CollectionUtils.isEmpty(specGroupList)){
            throw new LyException(ExceptionEnum.SPECGROUP_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(specGroupList,SpecGroupDTO.class);
    }

    public List<SpecParamDTO> querySpecParams(Long gid,Long cid,Boolean searching) {

        SpecParam record = new SpecParam();
        record.setGroupId(gid);
        record.setCid(cid);
        record.setSearching(searching);

        List<SpecParam> specParamList = this.specParamMapper.select(record);

        if (CollectionUtils.isEmpty(specParamList)){
            throw new LyException(ExceptionEnum.SPECPARAM_NOT_FOUND);
        }

        return BeanHelper.copyWithCollection(specParamList,SpecParamDTO.class);
    }

    public List<SpecGroupDTO> querySpecsByCid(Long id){
        List<SpecGroupDTO> groupList = queryGroupByCategory(id);
        List<SpecParamDTO> params = querySpecParams(null, id, null);
        Map<Long,List<SpecParamDTO>> paramMap=params.stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        for(SpecGroupDTO groupDTO:groupList){
            groupDTO.setParams(paramMap.get(groupDTO.getId()));
        }
        return groupList;
    }
}
